package com.sun.audit.intercept;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.mysql.cj.log.Log;
import com.sun.audit.entity.StatementAnalysis;
import com.sun.audit.enums.UpdateType;
import com.sun.audit.handle.AuditLogHandler;
import com.sun.audit.resolver.EntityClassResolver;
import com.sun.audit.resolver.EntityIdResolver;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Intercepts({
        @Signature(
                type = Executor.class,
                method = "update",
                args = {MappedStatement.class, Object.class}
        )
})
@Component
public class AuditLogInterceptor implements Interceptor {

    private ApplicationContext applicationContext;

    private AuditLogHandler auditLogHandler;

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void setAuditLogHandler(AuditLogHandler auditLogHandler) {
        this.auditLogHandler = auditLogHandler;
    }

    // 缓存 MappedStatement 的分析结果
    private final Map<String, StatementAnalysis> statementAnalysisCache = new ConcurrentHashMap<>();

    // 配置选项
    private boolean enabled = true;
    private boolean logUnchanged = false;
    // 是否跳过 XML 方式的更新
    private boolean skipXmlUpdates = false;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        log.info("statementAnalysisCache :{}", JSON.toJSONString(statementAnalysisCache));
        if (!enabled) {
            return invocation.proceed();
        }

        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];

        // 只处理更新操作
        if (ms.getSqlCommandType() != SqlCommandType.UPDATE) {
            return invocation.proceed();
        }

        try {
            // 分析 SQL 语句类型
            StatementAnalysis analysis = analyzeStatement(ms, parameter);
            // 根据分析结果选择处理策略
            switch (analysis.getUpdateType()) {
                case XML_SQL:
                    log.info("正在处理 XML SQL 方式的更新记录");
                    if (skipXmlUpdates) {
                        log.info("跳过 XML SQL 方式的更新记录");
                        return invocation.proceed();
                    }
                    return handleXmlUpdate(invocation, ms, parameter, analysis);
                case ENTITY:
                    log.info("正在处理实体对象方式的更新记录");
                    return handleEntityUpdate(invocation, ms, parameter, analysis);
                case WRAPPER:
                    log.info("正在处理 Wrapper 对象方式的更新记录");
                    return handleWrapperUpdate(invocation, ms, parameter, analysis);
                case UNKNOWN:
                default:
                    log.info("未知更新类型，跳过字段变更记录");
                    return invocation.proceed();
            }
        } catch (Exception e) {
            log.info("字段变更记录处理失败，继续执行更新操作", e);
            return invocation.proceed();
        }
    }

    @Override
    public Object plugin(Object target) {
//        log.info("========== 为 {} 创建代理 ==========", target.getClass().getSimpleName());
        return Interceptor.super.plugin(target);
    }

    /**
     * 一、处理 XML SQL 方式的更新
     */
    private Object handleXmlUpdate(Invocation invocation, MappedStatement ms, Object parameter, StatementAnalysis analysis) throws Throwable {
        Class<?> entityClass = analysis.getEntityClass();
        if (entityClass == null) {
            log.info("无法确定实体类型，跳过 XML 更新记录");
            return invocation.proceed();
        }
        // 构建查询条件
        QueryWrapper<?> queryWrapper = buildQueryWrapperForXml(ms, parameter, analysis);
        if (queryWrapper == null) {
            log.info("无法构建 XML 更新的查询条件，跳过记录");
            return invocation.proceed();
        }
        // 查询更新前的记录
        List<?> beforeList = queryBeforeUpdate(ms, queryWrapper, entityClass, analysis.getMapperClass());
        if (beforeList.isEmpty()) {
            log.info("更新前未找到匹配的记录，跳过字段变更记录");
            return invocation.proceed();
        }
        log.info("正在记录字段变更，更新前的记录：{}", JSON.toJSONString(beforeList));
        // 执行更新操作
        Object result = invocation.proceed();
        // 使用相同的条件查询更新后的记录
        List<?> afterList = queryAfterUpdate(ms, queryWrapper, entityClass, analysis.getMapperClass());
        log.info("正在记录字段变更，更新后的记录：{}", JSON.toJSONString(afterList));
        // 保存日志
        auditLogHandler.handleBatch(applicationContext, entityClass, beforeList, afterList);
        return result;
    }

    /**
     * 二、处理实体方式的更新
     */
    private Object handleEntityUpdate(Invocation invocation, MappedStatement ms, Object parameter, StatementAnalysis analysis) throws Throwable {
        Class<?> entityClass = analysis.getEntityClass();
        if (entityClass == null) {
            return invocation.proceed();
        }
        // 提取实体对象
        Object entity = extractEntityFromParameter(parameter, entityClass);
        if (entity == null) {
            log.info("未找到实体对象，跳过字段变更记录");
            return invocation.proceed();
        }
        // 构建查询条件（基于实体主键或所有非空字段）
        QueryWrapper<?> queryWrapper = buildQueryWrapperForEntity(entity, entityClass);
        if (queryWrapper == null) {
            log.info("无法构建实体更新的查询条件，跳过记录");
            return invocation.proceed();
        }
        // 查询更新前的记录
        List<?> beforeList = queryBeforeUpdate(ms, queryWrapper, entityClass, analysis.getMapperClass());
        if (beforeList.isEmpty()) {
            log.info("更新前未找到匹配的记录，跳过字段变更记录");
            return invocation.proceed();
        }
        // 执行更新操作
        Object result = invocation.proceed();
        // 使用相同的条件查询更新后的记录
        List<?> afterList = queryAfterUpdate(ms, queryWrapper, entityClass, analysis.getMapperClass());
        // 保存日志
        auditLogHandler.handleBatch(applicationContext, entityClass, beforeList, afterList);
        return result;
    }

    /**
     * 三、处理 Wrapper 方式的更新
     */
    private Object handleWrapperUpdate(Invocation invocation, MappedStatement ms, Object parameter, StatementAnalysis analysis) throws Throwable {
        Class<?> entityClass = analysis.getEntityClass();
        if (entityClass == null) {
            return invocation.proceed();
        }
        // 提取 UpdateWrapper
        UpdateWrapper<?> wrapper = extractWrapperFromParameter(parameter);
        if (wrapper == null) {
            log.info("未找到 UpdateWrapper，跳过字段变更记录");
            return invocation.proceed();
        }
        // 构建查询条件
        QueryWrapper<?> queryWrapper = buildQueryWrapperForWrapper(wrapper, entityClass);
        log.info("正在记录字段变更，构建查询条件：{}", JSON.toJSONString(queryWrapper));
        if (queryWrapper == null) {
            log.info("无法构建 Wrapper 更新的查询条件，跳过记录");
            return invocation.proceed();
        }
        // 查询更新前的记录
        List<?> beforeList = queryBeforeUpdate(ms, queryWrapper, entityClass, analysis.getMapperClass());
        if (beforeList.isEmpty()) {
            log.info("更新前未找到匹配的记录，跳过字段变更记录");
            return invocation.proceed();
        }
        // 执行更新操作
        Object result = invocation.proceed();
        // 使用相同的条件查询更新后的记录
        List<?> afterList = queryAfterUpdate(ms, queryWrapper, entityClass, analysis.getMapperClass());
        // 保存日志
        auditLogHandler.handleBatch(applicationContext, entityClass, beforeList, afterList);
        return result;
    }

    /**
     * 为 Wrapper 更新构建查询条件
     */
    private QueryWrapper<?> buildQueryWrapperForWrapper(UpdateWrapper<?> wrapper, Class<?> entityClass) {
        try {
            log.info("正在为 Wrapper 更新构建查询条件:{}",JSON.toJSONString(wrapper));
            // 尝试直接复制 UpdateWrapper 的条件
            QueryWrapper<Object> queryWrapper = new QueryWrapper<>();

            // 获取 UpdateWrapper 的表达式列表
            Field expressionField = AbstractWrapper.class.getDeclaredField("expression");
            expressionField.setAccessible(true);
            Object expression = expressionField.get(wrapper);

            // 复制表达式到 QueryWrapper
            Field queryExpressionField = AbstractWrapper.class.getDeclaredField("expression");
            queryExpressionField.setAccessible(true);
            queryExpressionField.set(queryWrapper, expression);

            // 复制参数名称值对
            Map<String, Object> paramNameValuePairs = wrapper.getParamNameValuePairs();
            Field paramField = AbstractWrapper.class.getDeclaredField("paramNameValuePairs");
            paramField.setAccessible(true);
            paramField.set(queryWrapper, new HashMap<>(paramNameValuePairs));

            return queryWrapper;

        } catch (Exception e) {
            log.info("转换 UpdateWrapper 到 QueryWrapper 失败", e);
            return null;
        }
    }

    /**
     * 从参数中提取 UpdateWrapper
     */
    private UpdateWrapper<?> extractWrapperFromParameter(Object parameter) {
        if (parameter instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> paramMap = (Map<String, Object>) parameter;
            // 检查 ew 参数
            log.info("检查ew参数:" + paramMap.containsKey("ew"));
            if (paramMap.containsKey("ew")) {
                Object ew = paramMap.get("ew");
                log.info("检查ew参数:" + ew.getClass());
                log.info("检查ew参数:{}", JSON.toJSONString(ew));
                log.info("检查ew参数:" + (ew instanceof UpdateWrapper));
                if (ew instanceof UpdateWrapper) {
                    return (UpdateWrapper<?>) ew;
                }
                if (ew instanceof LambdaUpdateWrapper) {
                    return buildUpdateWrapperFromLambda(ew);
                }
            }
        } else if (parameter instanceof UpdateWrapper) {
            return (UpdateWrapper<?>) parameter;
        }
        return null;
    }

    /**
     * 从 LambdaUpdateWrapper 构建 UpdateWrapper
     */
    private UpdateWrapper<?> buildUpdateWrapperFromLambda(Object lambdaWrapper) {
        UpdateWrapper<Object> updateWrapper = new UpdateWrapper<>();

        try {
            // 获取 LambdaUpdateWrapper 的类和方法
            Class<?> lambdaClass = lambdaWrapper.getClass();

            // 获取expression片段
            Field expressionField = lambdaClass.getSuperclass().getDeclaredField("expression");
            expressionField.setAccessible(true);
            @SuppressWarnings("unchecked")
            List<Object> expression = (List<Object>) expressionField.get(lambdaWrapper);

            Field queryExpressionField = AbstractWrapper.class.getDeclaredField("expression");
            queryExpressionField.setAccessible(true);
            queryExpressionField.set(updateWrapper, new ArrayList<>(expression));

            // 获取参数名称值对
            Field paramNameValuePairsField = lambdaClass.getSuperclass().getDeclaredField("paramNameValuePairs");
            paramNameValuePairsField.setAccessible(true);
            @SuppressWarnings("unchecked")
            Map<String, Object> paramNameValuePairs = (Map<String, Object>) paramNameValuePairsField.get(lambdaWrapper);

            Field queryParamNameValuePairsField = AbstractWrapper.class.getDeclaredField("paramNameValuePairs");
            queryParamNameValuePairsField.setAccessible(true);
            queryParamNameValuePairsField.set(updateWrapper, new HashMap<>(paramNameValuePairs));

            return updateWrapper;
        } catch (Exception e) {
            log.info("从 LambdaUpdateWrapper 构建 UpdateWrapper 失败", e);
            return null;
        }
    }

    /**
     * 为实体更新构建查询条件
     */
    private QueryWrapper<?> buildQueryWrapperForEntity(Object entity, Class<?> entityClass) {
        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        // 尝试使用主键
        Object idValue = extractIdValue(entity, entityClass);
        if (idValue != null) {
            queryWrapper.eq(getIdColumnName(entityClass), idValue);
            return queryWrapper;
        }
        // 使用所有非空字段作为条件
        Map<String, Object> nonNullFields = extractNonNullFields(entity, entityClass);
        for (Map.Entry<String, Object> entry : nonNullFields.entrySet()) {
            queryWrapper.eq(entry.getKey(), entry.getValue());
        }
        return nonNullFields.isEmpty() ? null : queryWrapper;
    }

    /**
     * 从实体对象中提取所有非空字段
     */
    private Map<String, Object> extractNonNullFields(Object entity, Class<?> entityClass) {
        Map<String, Object> fields = new HashMap<>();
        if (entity == null) {
            return fields;
        }
        Field[] allFields = entityClass.getDeclaredFields();
        for (Field field : allFields) {
            try {
                field.setAccessible(true);
                Object value = field.get(entity);

                if (value != null) {
                    fields.put(field.getName(), value);
                }
            } catch (IllegalAccessException e) {
                log.info("无法访问字段: {}", field.getName(), e);
            }
        }
        return fields;
    }

    /**
     * 获取主键列名
     */
    private String getIdColumnName(Class<?> entityClass) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
        if (tableInfo != null && tableInfo.getKeyProperty() != null) {
            return tableInfo.getKeyColumn();
        }
        return "id";
    }

    /**
     * 从实体对象中提取主键值
     */
    private Object extractIdValue(Object entity, Class<?> entityClass) {
        if (entity == null) {
            return null;
        }
        try {
            TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
            if (tableInfo != null && tableInfo.getKeyProperty() != null) {
                Field idField = entityClass.getDeclaredField(tableInfo.getKeyProperty());
                idField.setAccessible(true);
                return idField.get(entity);
            }
        } catch (Exception e) {
            log.info("无法提取主键值", e);
        }
        return null;
    }

    /**
     * 从参数中提取实体对象
     */
    private Object extractEntityFromParameter(Object parameter, Class<?> entityClass) {
        if (parameter instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> paramMap = (Map<String, Object>) parameter;

            // 检查 et 参数
            if (paramMap.containsKey("et")) {
                Object et = paramMap.get("et");
                if (et != null && entityClass.isInstance(et)) {
                    return et;
                }
            }

            // 检查其他可能的实体参数
            for (Object value : paramMap.values()) {
                if (value != null && entityClass.isInstance(value)) {
                    return value;
                }
            }
        } else if (parameter != null && entityClass.isInstance(parameter)) {
            return parameter;
        }

        return null;
    }


    /**
     * 查询更新后的数据
     */
    private List<?> queryAfterUpdate(MappedStatement ms, QueryWrapper<?> queryWrapper, Class<?> entityClass, Class<?> mapperClass) {
        return queryBeforeUpdate(ms, queryWrapper, entityClass, mapperClass);
    }

    /**
     * 分析 SQL 语句类型
     */
    private StatementAnalysis analyzeStatement(MappedStatement ms, Object parameter) {
        log.info("analyzeStatement parameter: {}", JSON.toJSONString(parameter));
        String msId = ms.getId();
        log.info("analyzeStatement msId: {}", msId);

        // 先从缓存中获取
        StatementAnalysis cachedAnalysis = statementAnalysisCache.get(msId);
        if (cachedAnalysis != null) {
            return cachedAnalysis;
        }

        StatementAnalysis analysis = new StatementAnalysis();
        analysis.setStatementId(msId);

        try {
            // 获取 SQL 源
            String sql = ms.getSqlSource().getBoundSql(null).getSql();
            log.info("analyzeStatement SQL: {}", sql);
            analysis.setSql(sql);

            Map<String, Object> paramMap = new HashMap<>();
            if (parameter instanceof Map) {
                paramMap = (Map<String, Object>) parameter;
            }

            // 分析 SQL 语句特征
            if (isMyBatisPlusWrapperSql(sql, paramMap)) {
                analysis.setUpdateType(UpdateType.WRAPPER);
            } else if (isEntityUpdateSql(sql, paramMap)) {
                analysis.setUpdateType(UpdateType.ENTITY);
            } else {
                analysis.setUpdateType(UpdateType.XML_SQL);
            }

            // 获取实体类型
            Class<?> entityClass = EntityClassResolver.resolve(ms, parameter);
            log.info("analyzeStatement entityClass: {}", entityClass);
            analysis.setEntityClass(entityClass);

            // 获取 Mapper 类
            Class<?> mapperClass = getMapperClass(ms);
            log.info("analyzeStatement mapperClass: {}", mapperClass);
            analysis.setMapperClass(mapperClass);

            // 对于 XML SQL，尝试解析 WHERE 条件字段
            if (analysis.getUpdateType() == UpdateType.XML_SQL && entityClass != null) {
                analyzeXmlWhereConditions(ms, analysis);
            }

        } catch (Exception e) {
            log.info("分析 SQL 语句失败: {}", msId, e);
            analysis.setUpdateType(UpdateType.UNKNOWN);
        }

        // 缓存分析结果
        statementAnalysisCache.put(msId, analysis);
        return analysis;
    }

    /**
     * 获取 Mapper 类
     */
    private Class<?> getMapperClass(MappedStatement ms) {
        try {
            String msId = ms.getId();
            // MappedStatement ID 格式通常是 "包名.类名.方法名"
            int lastDotIndex = msId.lastIndexOf(".");
            if (lastDotIndex <= 0) {
                return null;
            }

            String className = msId.substring(0, lastDotIndex);
            return Class.forName(className);
        } catch (Exception e) {
            log.info("获取 Mapper 类失败", e);
            return null;
        }
    }

    /**
     * 判断是否为 MyBatis-Plus Wrapper SQL
     */
    private boolean isMyBatisPlusWrapperSql(String sql, Map<String, Object> paramMap) {
        return paramMap.containsKey("ew");
    }

    /**
     * 判断是否为实体更新 SQL
     */
    private boolean isEntityUpdateSql(String sql, Map<String, Object> paramMap) {
        return paramMap.containsKey("et");
    }

    /**
     * 分析 XML SQL 的 WHERE 条件字段
     */
    private void analyzeXmlWhereConditions(MappedStatement ms, StatementAnalysis analysis) {
        try {
            BoundSql boundSql = ms.getSqlSource().getBoundSql(null);
            String sql = boundSql.getSql();
            log.info("analyzeXmlWhereConditions SQL: {}", sql);

            // 提取 WHERE 子句
            String whereClause = extractWhereClause(sql);
            log.info("analyzeXmlWhereConditions whereClause: {}", whereClause);
            if (whereClause != null) {
                // 解析 WHERE 条件中的字段
                Set<String> conditionFields = parseConditionFields(whereClause);
                analysis.setConditionFields(conditionFields);

                // 尝试识别主键条件
                Optional<String> idField = conditionFields.stream()
                        .filter(field -> field.equalsIgnoreCase("id") || field.endsWith("Id"))
                        .findFirst();

                if (idField.isPresent()) {
                    analysis.setPrimaryKeyField(idField.get());
                }
            }
        } catch (Exception e) {
            log.info("分析 XML WHERE 条件失败", e);
        }
    }

    /**
     * 提取 WHERE 子句
     */
    private String extractWhereClause(String sql) {
        int whereIndex = sql.toUpperCase().indexOf("WHERE");
        if (whereIndex >= 0) {
            return sql.substring(whereIndex + 5).trim();
        }
        return null;
    }

    /**
     * 解析WHERE条件中的字段
     */
    private Set<String> parseConditionFields(String whereClause) {
        Set<String> fields = new HashSet<>();

        // 简单的字段名提取（实际应用可能需要更复杂的解析）
        Pattern pattern = Pattern.compile("(\\w+)\\s*[=<>]");
        Matcher matcher = pattern.matcher(whereClause);

        while (matcher.find()) {
            fields.add(matcher.group(1));
        }
        log.info("parseConditionFields fields: {}", JSON.toJSONString(fields));
        return fields;
    }

    /**
     * 为 XML SQL 构建查询条件
     */
    private QueryWrapper<?> buildQueryWrapperForXml(MappedStatement ms, Object parameter, StatementAnalysis analysis) {
        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        try {
            BoundSql boundSql = ms.getBoundSql(parameter);
            log.info("buildQueryWrapperForXml SQL: {}", JSON.toJSONString(boundSql));
            Configuration configuration = ms.getConfiguration();
            // 获取参数映射
            List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
            log.info("buildQueryWrapperForXml parameterMappings: {}", JSON.toJSONString(parameterMappings));
            Object parameterObject = boundSql.getParameterObject();
            log.info("buildQueryWrapperForXml parameterObject: {}", JSON.toJSONString(parameterObject));
            // 提取 WHERE 条件值
            Map<String, Object> conditionValues = extractXmlConditionValues(analysis.getConditionFields(), parameterMappings, parameterObject, configuration);
            log.info("buildQueryWrapperForXml conditionValues: {}", JSON.toJSONString(conditionValues));
            // 应用到 QueryWrapper
            for (Map.Entry<String, Object> entry : conditionValues.entrySet()) {
                queryWrapper.eq(entry.getKey(), entry.getValue());
            }
            return queryWrapper;
        } catch (Exception e) {
            log.info("构建 XML 查询条件失败", e);
            return null;
        }
    }

    /**
     * 提取 XML SQL 的条件值
     */
    private Map<String, Object> extractXmlConditionValues(Set<String> conditionFields,
                                                          List<ParameterMapping> parameterMappings,
                                                          Object parameterObject,
                                                          Configuration configuration) {
        Map<String, Object> conditionValues = new HashMap<>();
        if (conditionFields == null || conditionFields.isEmpty()) {
            return conditionValues;
        }
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
        for (ParameterMapping mapping : parameterMappings) {
            String property = mapping.getProperty();
            // 检查是否为条件字段
            if (conditionFields.contains(property)) {
                try {
                    Object value;
                    if (metaObject != null && metaObject.hasGetter(property)) {
                        value = metaObject.getValue(property);
                    } else if (parameterObject instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> paramMap = (Map<String, Object>) parameterObject;
                        value = paramMap.get(property);
                    } else {
                        value = null;
                    }
                    if (value != null) {
                        conditionValues.put(property, value);
                    }
                } catch (Exception e) {
                    log.info("提取参数值失败: {}", property, e);
                }
            }
        }
        return conditionValues;
    }

    /**
     * 查询更新前的数据
     */
    private List<?> queryBeforeUpdate(MappedStatement ms, QueryWrapper<?> queryWrapper, Class<?> entityClass, Class<?> mapperClass) {
        try {
            // 直接使用Spring管理的SqlSession或通过ApplicationContext获取
            if (applicationContext == null) {
                log.info("ApplicationContext未设置，跳过查询");
                return Collections.emptyList();
            }

            // 通过ApplicationContext获取SqlSessionTemplate或SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
            if (sqlSessionFactory == null) {
                log.info("SqlSessionFactory未在ApplicationContext容器中获取到，跳过查询");
                return Collections.emptyList();
            }
            try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
                if (mapperClass == null) {
                    log.info("无法获取 Mapper 类，跳过查询");
                    return Collections.emptyList();
                }
                Object mapper = sqlSession.getMapper(mapperClass);
                Method selectListMethod = findSelectListMethod(mapper.getClass());
                log.info("queryBeforeUpdate selectListMethod: {}", JSON.toJSONString(selectListMethod));
                if (selectListMethod != null) {
                    @SuppressWarnings("unchecked")
                    List<Object> result = (List<Object>) selectListMethod.invoke(mapper, queryWrapper);
                    log.info("queryBeforeUpdate result: {}", JSON.toJSONString(result));
                    return result;
                }
            }
        } catch (Exception e) {
            log.info("查询更新前数据失败", e);
        }

        return Collections.emptyList();
    }

    /**
     * 查找 selectList 方法
     */
    private Method findSelectListMethod(Class<?> mapperClass) {
        for (Method method : mapperClass.getMethods()) {
            if ("selectList".equals(method.getName()) &&
                    method.getParameterCount() == 1 &&
                    method.getParameterTypes()[0].getName().contains("Wrapper")) {
                return method;
            }
        }
        return null;
    }

    // 获取实体对象
    private Object fetchEntityById(Class<?> entityClass, Object idValue) {
        if (applicationContext == null) {
            throw new IllegalStateException("ApplicationContext has not been set");
        }

        // 获取Mapper实例（约定：实体类名 + "Mapper"）
        String mapperBeanName = String.format("%sMapper", entityClass.getSimpleName().replaceAll("PO", ""));
        mapperBeanName = Character.toLowerCase(mapperBeanName.charAt(0)) + mapperBeanName.substring(1);

        Object mapper = applicationContext.getBean(mapperBeanName);
        if (mapper == null) {
            throw new RuntimeException("Mapper not found for entity: " + entityClass.getName());
        }

        try {
            Method[] methods = mapper.getClass().getMethods();
            for (Method method : methods) {
                if ("selectById".equals(method.getName())) {
                    return method.invoke(mapper, idValue);
                }
            }
        } catch (Exception e) {
            log.info("========== 获取修改前实例的方法异常 ==========", e);
        }
        return null;
    }

}